package com.falcon.mojo.v1;

import com.falcon.mojo.AbsMojo;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;

import java.io.File;

/** 编译前合并源码、资源模块 */
@Mojo(name = "add-compile-source", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class AddCompileSourceMojo extends AbsMojo {

    public void execute() throws MojoExecutionException, MojoFailureException {

        // 获取要合并的模块列表
        File[] modules = enableIncludeModules ? includeModules : getSubModules();

        // 添加源码目录
        addSource(modules);

        // 添加资源目录
        addResource(modules);
    }

    // 添加资源
    private void addSource(File[] subModules) {
        for (File subModule : subModules) {
            String sourceDir = subModule.getAbsolutePath() + File.separator + "src/main/java";
            this.project.addCompileSourceRoot(sourceDir);
            getLog().info("新增源码目录: " + sourceDir);

            String testSourceDir = subModule.getAbsolutePath() + File.separator + "src/test/java";
            if (new File(testSourceDir).exists()) {
                this.project.addTestCompileSourceRoot(testSourceDir);
                getLog().info("新增测试源码目录: " + testSourceDir);
            }
        }
    }

    // 添加资源
    private void addResource(File[] subModules) {
        for (File subModule : subModules) {
            String resourceDir = subModule.getAbsolutePath() + File.separator + "src/main/resources";
            if (new File(resourceDir).exists()) {
                this.project.addResource(newResource(resourceDir));
                getLog().info("新增资源目录: " + resourceDir);
            }

            String testResourceDir = subModule.getAbsolutePath() + File.separator + "src/test/resources";
            if (new File(testResourceDir).exists()) {
                this.project.addResource(newResource(testResourceDir));
                getLog().info("新增测试资源目录: " + testResourceDir);
            }
        }
    }

    private Resource newResource(String directory) {
        Resource resource = new Resource();
        resource.setDirectory(directory);
        return resource;
    }

}
